// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database();
const _ = db.command;
const yqm = {
  admin: 'abcacb',
  conmon: 'qkazs'
}

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let _openid = wxContext.OPENID
  const res = {
    status: 0,
    message: ''
  }

  const {
    type,
    userInfo,
    userWxInfo
  } = event
  let time= new Date().getTime();
  const logndata = {
    _openid,
    userWxInfo,
    admin: false,
    joinner: false,
    time
  }
  let procount = await db.collection('user').where({
    _openid
  }).count()
  switch (type) {
    case 'xuanshou': {
      logndata.jonnerName = userInfo.username
      if (userInfo.password == yqm.admin) {
        logndata.admin = true
        logndata.joinner = true
      }
      if (userInfo.password == yqm.conmon) {
        logndata.joinner = true
      }

      if (!logndata.admin && !logndata.joinner) {
        res.status=0
        res.message = '非法邀请码'
        return res
      } else {

        let procount0=await db.collection('user').where({
          _openid:_.neq(_openid),
          jonnerName:logndata.jonnerName
        }).count()
        if(procount0.total ==1){
          res.status=0
          res.message=`《${logndata.jonnerName}》已被注册`
          return res
        }
        if (procount.total == 1) {
          let proUp = await db.collection('user').where({
            _openid
          }).update({
            data: logndata
          });
          if (proUp.stats.updated==1){
            res.status=1
            let sf = logndata.admin ? '管理员' : '成员'
            res.message=`${logndata.jonnerName}以《${sf}》身份报名成功`
          }
          else{
            res.status=0
            res.message='报名失败,系统错误'
          }
          return res
        }
        logndata.jf=0
        let proadd = await db.collection('user').add({
          data: logndata
        })
        if (proadd._id) {
          res.status=1
          let sf = logndata.admin ? '管理员' : '成员'
          res.message = `${logndata.jonnerName}以《${sf}》身份报名成功`
        } else {
          res.message = '报名失败,系统错误'
        }
        return res
      }
    }
    break;

    case 'youke': {
      if (procount.total==1){
        res.status=1
        res.message='你已经游客进入过'
        return res
      }
      logndata.jf=0
      let proadd = await db.collection('user').add({
        data: logndata
      })
      if(proadd._id){
        res.status=1
        res.message='游客记录成功'
      }
      else{
        res.status=0
        res.message='系统错误,游客登录失败'
      }
      return res
    }
    break;
  }

  return res
}